package com.cy.cqb.dockerjava.controller;

import com.cy.cqb.dockerjava.service.DockerClientService;
import com.github.dockerjava.api.DockerClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * Hello Controller
 * </p>
 *
 * @package: com.xkcoding.docker.controller
 * @description: Hello Controller
 * @author: yangkai.shen
 * @date: Created in 2018-11-29 14:58
 * @copyright: Copyright (c) 2018
 * @version: V1.0
 * @modified: yangkai.shen
 */
@RestController
@RequestMapping
public class DockerTestController {
//    @Value("${dockerContainerId}")
//    private String getDockerContainerId;
//    @Value("${dockerStart.cmd}")
//    private String dockerStartCmd;
    @Autowired
    private Shell shell2;

    @Autowired
    private DockerClientService dockerClientService;

    @GetMapping
    public String hello() {
        return "Hello,From Docker!";
    }
    @GetMapping("/test")
    public String testDocker(){
        DockerClient dockerClient =dockerClientService.connectDocker();
        //dockerClientService.createContainers(dockerClient,"redisConnect","redis",6379,6379);
        System.out.println(dockerClient);
        return "success!";
    }

    /**
     * 启动已存的容器
     * @return
     */
    @GetMapping("/start")
    public String startDockerContainer(){
        DockerClient dockerClient =dockerClientService.connectDocker();
        dockerClientService.startContainer(dockerClient,"0af1e1b9e7c1");
        return "start";
    }

    /**
     * 启动liunx脚本（更改脚本内容控制docker容器的启动和销毁）
     */
    @GetMapping("/startShell")
    public String startLinuxShell(){
        try {
            //准备脚本
            String cmd = "sh /home/ubuntu/test/test.sh";
            //String cmd = dockerStartCmd;
            System.out.println("cmd = "+ cmd);
            Process proc = Runtime.getRuntime().exec(cmd);
            /**
             * 可执行程序的输出可能会比较多，而运行窗口的输出缓冲区有限，会造成waitFor一直阻塞。
             * 解决的办法是，利用Java提供的Process类提供的getInputStream,getErrorStream方法
             * 让Java虚拟机截获被调用程序的标准输出、错误输出，在waitfor()命令之前读掉输出缓冲区中的内容。
             */
            String flag ;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            while ( (flag=bufferedReader.readLine()) != null){
                System.out.println("result ---- "+flag);
            }
            bufferedReader.close();
            /**
             * 等待脚本执行完成
             */
            proc.waitFor();

        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
        return "start ok!";
    }

    /**
     * 停止容器的liunx脚本（更改脚本内容控制docker容器的启动和销毁）
     */
    @GetMapping("/stopShell")
    public String stopLinuxShell(){
        try {
            //准备脚本
            String cmd = "sh /home/ubuntu/test/stop.sh";
            //String cmd = dockerStartCmd;
            System.out.println("cmd = "+ cmd);
            Process proc = Runtime.getRuntime().exec(cmd);
            /**
             * 可执行程序的输出可能会比较多，而运行窗口的输出缓冲区有限，会造成waitFor一直阻塞。
             * 解决的办法是，利用Java提供的Process类提供的getInputStream,getErrorStream方法
             * 让Java虚拟机截获被调用程序的标准输出、错误输出，在waitfor()命令之前读掉输出缓冲区中的内容。
             */
            String flag ;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            while ( (flag=bufferedReader.readLine()) != null){
                System.out.println("result ---- "+flag);
            }
            bufferedReader.close();
            /**
             * 等待脚本执行完成
             */
            proc.waitFor();

        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
        return "stop ok!";
    }

    @GetMapping("/startShell2")
    public String startLinuxShell2() throws Exception {
        shell2.runShell("/home/ubuntu/test/test.sh arg1 arg2 arg3");
        return "start ok";
    }
}
